package com.jinkeen.xiaxie.viewPager2

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.fragment.app.*
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.jinkeen.xiaxie.databinding.ActivityViewPager2Binding

class ViewPager2Activity : FragmentActivity() {

    private lateinit var binding: ActivityViewPager2Binding

    private lateinit var fragments:ArrayList<Fragment>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityViewPager2Binding.inflate(layoutInflater)
        setContentView(binding.root)
        fragments=ArrayList()
        fragments.add(Fragment_01())
        fragments.add(Fragment_02())
        fragments.add(Fragment_01())
        fragments.add(Fragment_02())
        fragments.add(Fragment_01())
        val pagerAdapter = ScreenSlidePagerAdapter(this,fragments)
        binding.viewpager02.adapter = pagerAdapter
    }

    override fun onBackPressed() {
        if (binding.viewpager02.currentItem == 0) {
            super.onBackPressed()
        } else {
            binding.viewpager02.currentItem = binding.viewpager02.currentItem - 1
        }
    }

    private inner class ScreenSlidePagerAdapter(fa: FragmentActivity,private val fragmentList:ArrayList<Fragment>) : FragmentStateAdapter(fa) {
        override fun getItemCount() = fragments.size

        override fun createFragment(position: Int): Fragment = fragmentList[position]

    }
}